package cn.relx.order.service.impl;

import cn.relx.basic.config.BussinessException;
import cn.relx.order.domain.OrderPetAcquisition;
import cn.relx.order.dto.OrderDto;
import cn.relx.order.mapper.OrderPetAcquisitionMapper;
import cn.relx.order.service.IOrderPetAcquisitionService;
import cn.relx.basic.service.impl.BaseServiceImpl;
import cn.relx.pet.domain.PetSalesmanReimbursement;
import cn.relx.pet.mapper.PetSalesmanReimbursementMapper;
import cn.relx.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author relx
 * @since 2022-11-02
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetSalesmanReimbursementMapper petSalesmanReimbursementMapper;

    @Override
    public void cancel(Long id) {
        orderPetAcquisitionMapper.cancel(id);
    }

    /**
     * 确认订单
     * @param orderDto
     * @param loginUser
     */
    @Override
    @Transactional
    public void confirmOrderAndSaveLog(OrderDto orderDto, Logininfo loginUser) {
        updateOrderAndSaveLog(orderDto, loginUser);
    }

    /**
     * 修改订单 状态、寻主信息
     * 保存日志
     * @param orderDto
     * @param loginUser
     */
    private void updateOrderAndSaveLog(OrderDto orderDto, Logininfo loginUser) {
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.findById(orderDto.getId());
        if (orderPetAcquisition == null){
            throw new BussinessException("订单不存在，请重新确认信息！");
        }
        if(orderPetAcquisition.getState() == 1){
            throw new BussinessException("订单已完成，请重新确认信息！");
        }
        if(orderPetAcquisition.getState() == -1){
            throw new BussinessException("订单异常，请重新确认信息！");
        }
        //修改订单状态和添加寻主信息
//        orderPetAcquisition.setPetId(orderDto.getPetId());
        orderPetAcquisition.setState(1);
        orderPetAcquisition.setPaytype(1);
        orderPetAcquisitionMapper.update(orderPetAcquisition);
        //生成报销收据
        PetSalesmanReimbursement petSalesmanReimbursement = new PetSalesmanReimbursement();
        petSalesmanReimbursement.setAdvancePaymentAmount(orderDto.getMoney());
        petSalesmanReimbursement.setSalesmanId(loginUser.getId());
        petSalesmanReimbursement.setSearchMasterMsgId(orderDto.getSearchMasterMsgId());
        petSalesmanReimbursement.setShopId(orderDto.getShopId());
        petSalesmanReimbursement.setNode("报销金额："+ orderDto.getMoney());
        petSalesmanReimbursementMapper.add(petSalesmanReimbursement);
    }
}
